const user_auths_model = require('../../models/user/user_auths');
const users_model = require('../../models/user/index');
const BaseComponent = require('../../prototype/baseComponent');
const { appId , secret } = require('../../config/index').wx_config
const axios = require('axios')
const log = console.log
class User extends BaseComponent {
  constructor() {
    super()
  }
  //注册

  register = (params) => {
    return new Promise(async (resolve, reject) => {
      try {
        let user_id = this.createId()
        let new_user_auth = {
          _id: user_id,
          password: params.password,
          phone: params.phone,
        }
        let reg = /^(\d{3})\d{4}(\d{4})$/;
        let nickname = params.phone.replace(reg, "$1****$2");
        let new_user = {
          _id: user_id,
          nickname: nickname,
          phone: params.phone,
        }
        await user_auths_model.create(new_user_auth)
        await users_model.create(new_user)
        resolve()
      } catch (err) {
        reject(err)
      }
    })
  }
  //登录
  login = (params, userInfo) => {
    return new Promise(async (resolve, reject) => {
      try {
        if (userInfo.password != params.password) throw new Error('密码错误')
        let token = await this.createToken(userInfo.toJSON())
        resolve(token)
        this.updateLoginTime(userInfo.user_id)
      } catch (err) {
        reject(err)
      }
    })
  }
  updateLoginTime = async (user_id) => {
    try {
      await users_model.updateOne({ user_id: user_id }, { $set: { last_time: Date.now() } })
    } catch (err) {
      this.error(`更新最后登录时间失败：${err}`)
    }
  }
  loginhandler = async (req, res, next) => {
    try {
      console.log(`qwe123`, 123)
      var params = req.body;
      await this.registerJoi(params)
      let userInfo = await user_auths_model.findOne({ "phone": params.phone }, { '_id': 0, '__v': 0 })
      if (!userInfo) {
        // 先注册再登录
        await this.register(params)
        userInfo = await user_auths_model.findOne({ "phone": params.phone }, { '_id': 0, '__v': 0 })
        let token = await this.login(params, userInfo)
        let resBody = {
          code: 0,
          data: {
            token: token
          },
          message: '登录成功'
        }
        res.send(resBody)
      } else {
        // 直接登录
        let token = await this.login(params, userInfo)
        let resBody = {
          code: 0,
          data: {
            token: token
          },
          message: '登录成功'
        }
        res.send(resBody)
      }
    } catch (error) {
      let body = {
        code: -1,
        message: error.message || '操作失败'
      }
      res.send(body)
    }
  }
  //小程序获取seesion
  miniProgramLogin = async (req, res, next) => {
    try {
      let { code } = req.body;
      let url = `https://api.weixin.qq.com/sns/jscode2session?appid=${appId}&secret=${secret}&js_code=${code}&grant_type=authorization_code`
      let { data } = await axios.get(url)
      if(data.errcode) throw new Error(data.errmsg)
      res.send(data);
    } catch (err) {
      let error = {
        code: -1,
        message: err.message || '操作失败'
      }
      res.send(error)
    }
  }
  //根据token获取用户信息
  getUserInfo = async (req, res, next) => {
    try {
      let token = req.headers.token
      if (!token) throw new Error('用户授权失效，请重新登录')
      let { user_id, status } = await this.decodedToken(token)
      let userInfo = await users_model.findOne({ "user_id": user_id }, { '_id': 0, '__v': 0 })
      if (!userInfo) throw new Error('用户不存在')
      userInfo = userInfo.toJSON()
      userInfo.status = status
      let body = {
        code: 0,
        data: userInfo,
        message: '查询成功'
      }
      res.send(body);
    } catch (err) {
      this.error(`获取用户信息失败：${err}`)
      let error = {
        code: -1,
        message: err.message || '操作失败'
      }
      res.send(error)
    }
  }
  //根据id获取用户信息
  getUserInfoById = async (req, res, next) => {
    try {
      let token = req.headers.token
      if (!token) throw new Error('用户授权失效，请重新登录')
      let { user_id } = req.query
      console.log(user_id)
      let userInfo = await users_model.findOne({ "user_id": user_id }, { '__v': 0 })
      if (!userInfo) throw new Error('用户不存在')
      console.log(userInfo)
      console.log(await user_auths_model.findOne({ "user_id": user_id }, { '_id': 0, '__v': 0 }))
      let { status } = await user_auths_model.findOne({ "user_id": user_id }, { '_id': 0, '__v': 0 })
      userInfo = userInfo.toJSON()
      userInfo.status = status
      let body = {
        code: 0,
        data: userInfo,
        message: '查询成功'
      }
      log(body)
      res.send(body);
    } catch (err) {
      this.error(`获取用户信息失败：${err}`)
      let error = {
        code: -1,
        message: err.message || '操作失败'
      }
      res.send(error)
    }
  }
  //获取用户列表
  getUserList = async (req, res, next) => {
    try {
      const { page = 1, limit = 10 } = req.query
      let userList = await users_model.find({}, { '__v': 0 }, { lean: true }).skip(Number((page-1) * limit)).limit(Number(limit))
      let total = await users_model.estimatedDocumentCount()
      // userList.forEach((item) => {
      //   item.register_time = this.formatTime(item.register_time)
      //   item.last_time = this.formatTime(item.last_time)
      //   item.birthday = this.formatTime(item.birthday)
      // })
      let body = {
        code: 0,
        data: {
          list: userList,
          total: total
        },
        message: '查询成功'
      }
      res.send(body);
    } catch (err) {
      this.error(`获取用户信息失败：${err}`)
      let error = {
        code: -1,
        message: err.message || '操作失败'
      }
      res.send(error)
    }
  }
  //修改用户资料
  updataUserInfo = async (req, res, next) => {
    try {
      // let token = req.headers.token
      // if (!token) throw new Error('用户授权失效，请重新登录')
      // let params = req.body
      // let val = await this.userJoi(params)
      // let { user_id } =  await this.decodedToken(token)
      let { user_id } = req.body
      console.log(req.body);
      let userInfo = await users_model.findOneAndUpdate({ user_id: user_id }, { $set: val })
      if (!userInfo) throw new Error('用户不存在')
      let body = {
        code: 0,
        message: '修改成功'
      }
      res.send(body)
    } catch (err) {
      this.error(`修改用户资料失败：${err}`)
      let error = {
        code: -1,
        message: err.message || '操作失败'
      }
      res.send(error)
    }
  }
  //更新手机号
  updatePhone = async (req, res, next) => {
    try {
      let token = req.headers.token
      if (!token) throw new Error('用户授权失效，请重新登录')
      let oldPhone = req.body.oldPhone
      let newPhone = req.body.newPhone
      if (!oldPhone || !newPhone) throw new Error('请输入手机号')
      var reg = /^[1][3,4,5,6,7,8,9][0-9]{9}$/
      if (!reg.test(oldPhone) || !reg.test(newPhone)) throw new Error('请输入正确的手机号')
      let { user_id } = await this.decodedToken(token)
      let userInfo = await user_auths_model.findOne({ "user_id": user_id })
      if (!userInfo) throw new Error('用户不存在')
      if (userInfo.phone != oldPhone) throw new Error('原始手机号输入不正确')
      await user_auths_model.findOneAndUpdate({ user_id: user_id }, { $set: { phone: newPhone } });
      let body = {
        code: 0,
        message: '修改成功'
      }
      res.send(body)
    } catch (err) {
      this.error(`更新密码失败：${err}`)
      let error = {
        code: -1,
        message: err.message || '操作失败'
      }
      res.send(error)
    }
  }
  //更新密码
  updataPassword = async (req, res, next) => {
    try {
      const token = req.headers.token
      if (!token) throw new Error('用户授权失效，请重新登录')
      const { oldPassword, newPassword, newPhone } = req.body
      let { user_id, oldPhone } = await this.decodedToken(token)
      if (newPhone != oldPhone) throw new Error('手机号输入不正确')
      let userInfo = await user_auths_model.findOne({ "user_id": user_id })
      if (!userInfo) throw new Error('用户不存在')
      if (userInfo.password != oldPassword) throw new Error('原始密码输入不正确')
      await user_auths_model.updateOne({ user_id: user_id }, { $set: { password: newPassword } });
      let body = {
        code: 0,
        message: '修改成功'
      }
      res.send(body)
    } catch (err) {
      this.error(`更新密码失败：${err}`)
      let error = {
        code: -1,
        message: err.message || '操作失败'
      }
      res.send(error)
    }
  }
  //重置密码
  resetPassword = async (req, res, next) => {
    try {
      const { newPassword, phone } = req.body
      let userInfo = await user_auths_model.findOne({ "phone": phone })
      if (!userInfo) throw new Error('用户不存在')
      await user_auths_model.updateOne({ phone: phone }, { $set: { password: newPassword } });
      let body = {
        code: 0,
        message: '修改成功'
      }
      res.send(body)
    } catch (err) {
      this.error(`重置密码失败：${err}`)
      let error = {
        code: -1,
        message: err.message || '操作失败'
      }
      res.send(error)
    }
  }
  //注销用户
  logoutUser = async (req, res, next) => {
    try {
      // const token = req.headers.token
      // if (!token) throw new Error('用户授权失效，请重新登录')
      const { user_id } = req.body
      if (!user_id) throw new Error('请填写用户id')
      let data = await user_auths_model.findOneAndRemove({ user_id: user_id })
      if (!data) throw new Error('用户不存在')
      await users_model.findOneAndRemove({ user_id: user_id })
      const body = {
        code: 0,
        message: '删除用户成功'
      }
      res.send(body)
    } catch (err) {
      this.error(`删除用户失败：${err}`)
      let error = {
        code: -1,
        message: err.message || '操作失败'
      }
      res.send(error)
    }
  }
}
module.exports = new User()